﻿
<CascadingValue Value="this">
    <div class="form-inline">
        @if (!string.IsNullOrEmpty(PreText))
        {
            <label>@PreText</label>
        }
        <div class="form-check form-switch">
            <input class="form-check-input"
                   type="checkbox"
                   checked="@IsChecked()"
                   disabled="@IsDisabled()"
                   onchange="@(async (ChangeEventArgs e) => await UpdateCheck(Convert.ToBoolean(e.Value)))">
            @if (!string.IsNullOrEmpty(Text))
            {
                <label>@Text</label>
            }
            @ChildContent
        </div>
    </div>
</CascadingValue>

@code {
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    /// <summary>
    /// Switch pre-text.
    /// </summary>
    [Parameter]
    public string? PreText { get; set; }

    /// <summary>
    /// Switch text.
    /// </summary>
    [Parameter]
    public string? Text { get; set; }


    /// <summary>
    /// Is switch disabled
    /// </summary>
    [Parameter]
    public bool Disabled { get; set; }

    /// <summary>
    /// Is switch checked
    /// </summary>
    [Parameter]
    public bool Value { get; set; }


    private string? IsChecked()
    {
        return Value ? "checked" : null;
    }

    private string? IsDisabled()
    {
        return Disabled ? "disabled" : null;
    }

    private async Task UpdateCheck(bool value)
    {
        if (Value != value)
        {
            Value = value;
            await ValueChanged.InvokeAsync();
            if (OnChange != null)
            {
                OnChange(value);
            }
        }
    }

    /// <summary>
    /// Receive notification when user changes the value.
    /// </summary>
    [Parameter]
    public EventCallback<bool> ValueChanged { get; set; }

    /// <summary>
    /// Receive notification when user changes the value.
    /// </summary>
    [Parameter]
    public Action<bool>? OnChange { get; set; }
}